package com.kitchen.util;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 文件工具类 - I/O流操作
 * 用于日志记录和数据备份
 */
public class FileUtil {
    private static final String LOG_DIR = "logs";
    private static final String BACKUP_DIR = "backup";
    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    
    static {
        // 创建必要的目录
        File logDir = new File(LOG_DIR);
        if (!logDir.exists()) {
            logDir.mkdirs();
        }
        File backupDir = new File(BACKUP_DIR);
        if (!backupDir.exists()) {
            backupDir.mkdirs();
        }
    }
    
    /**
     * 写入日志文件
     */
    public static void writeLog(String message) {
        String logFile = LOG_DIR + File.separator + "system_" + 
                         LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")) + ".log";
        
        try (BufferedWriter writer = new BufferedWriter(
                new OutputStreamWriter(new FileOutputStream(logFile, true), StandardCharsets.UTF_8))) {
            String logEntry = "[" + LocalDateTime.now().format(DATE_FORMATTER) + "] " + message;
            writer.write(logEntry);
            writer.newLine();
            writer.flush();
        } catch (IOException e) {
            System.err.println("写入日志失败: " + e.getMessage());
        }
    }
    
    /**
     * 备份数据到文件
     */
    public static void backupData(String data, String fileName) {
        String backupFile = BACKUP_DIR + File.separator + fileName + "_" + 
                           LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss")) + ".txt";
        
        try (BufferedWriter writer = new BufferedWriter(
                new OutputStreamWriter(new FileOutputStream(backupFile), StandardCharsets.UTF_8))) {
            writer.write(data);
            writer.flush();
            FileUtil.writeLog("数据备份成功: " + backupFile);
        } catch (IOException e) {
            FileUtil.writeLog("数据备份失败: " + e.getMessage());
            throw new RuntimeException("数据备份失败", e);
        }
    }
    
    /**
     * 读取文件内容
     */
    public static String readFile(String filePath) {
        StringBuilder content = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(new FileInputStream(filePath), StandardCharsets.UTF_8))) {
            String line;
            while ((line = reader.readLine()) != null) {
                content.append(line).append("\n");
            }
        } catch (IOException e) {
            throw new RuntimeException("读取文件失败: " + e.getMessage(), e);
        }
        return content.toString();
    }
}

